package org.zyx.goods.service;

import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.zyx.goods.utils.ThreadUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

/**
 * @Author: SwordMaple
 * @Date: 2020/10/15  20:37
 * @Description: 页面静态化服务
 * @Version: 1.0
 */
@Service
public class GoodsHtmlService {

    @Resource
    private TemplateEngine engine;
    @Resource
    private GoodsService goodsService;

    /**
     * 生成静态页面
     * @param spuId 商品集id
     */
    public void createHtml(Long spuId) {

        //1.初始化运行上下文
        Context context = new Context();
        //2.设置数据模型
        context.setVariables(goodsService.loadData(spuId));
        //3.io流,将静态页面保存到本地文件
        PrintWriter printWriter = null;
        try {
            File file = new File("E:\\WorkTools\\Nginx\\nginx-1.19.1\\html\\item\\"+spuId+".html");
            printWriter = new PrintWriter(file);
            engine.process("item",context,printWriter);//需要提前执行,避免io流被关闭
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            if(printWriter != null){
                printWriter.close();
            }
        }

    }


    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(()->createHtml(spuId));
        /*ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });*/
    }

    /**
     * 删除静态界面
     * @param spuId
     */
    public void deleteHtml(Long spuId){
        File file = new File("E:\\WorkTools\\Nginx\\nginx-1.19.1\\html\\item\\" + spuId + ".html");
        file.deleteOnExit();//存在就删除该文件
    }


}
